from datetime import datetime
import os

from django.conf import settings
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
import json

from envs.models import Envs
from modulars.models import Modulars
from utils import handle_datas
from .models import Testcases
from testcases import serializers
from utils import common


class TestcasesViewSet(ModelViewSet):
    """
    list:
    返回用例(多个)列表数据

    create:
    创建用例

    retrieve:
    返回用例(单个)详情数据

    update:
    更新(全部)用例

    partial_update:
    更新(部分)用例

    destroy:
    删除用例

    run:
    运行用例
    """
    queryset = Testcases.objects.filter(is_delete=False)
    serializer_class = serializers.TestcasesSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()     #逻辑删除

    def retrieve(self, request, *args, **kwargs):
        """获取用例详情信息"""
        # Testcase对象
        testcase_obj = self.get_object()

        # 用例前置信息
        testcase_include = json.loads(testcase_obj.include, encoding='utf-8')

        # 用例请求信息
        testcase_request = json.loads(testcase_obj.request, encoding='utf-8')
        testcase_request_datas = testcase_request.get('test').get('request')

        # 处理用例的validate变量列表
        testcase_validate = testcase_request.get('test').get('validate')
        testcase_validate_list = handle_datas.handle_data1(testcase_validate)

        # 处理用例的param数据
        testcase_params = testcase_request_datas.get('params')
        testcase_params_list = handle_datas.handle_data4(testcase_params)

        # 处理用例的header列表
        testcase_headers = testcase_request_datas.get('headers')
        testcase_headers_list = handle_datas.handle_data4(testcase_headers)

        # 处理用例variables全局变量列表
        testcase_variables = testcase_request.get('test').get('variables')
        testcase_variables_list = handle_datas.handle_data2(testcase_variables)

        # 处理form表单数据
        testcase_form_datas = testcase_request_datas.get('data')
        testcase_form_datas_list = handle_datas.handle_data6(testcase_form_datas)

        # 处理json数据
        testcase_json_datas = json.dumps(testcase_request_datas.get('json'), ensure_ascii=False)

        # 处理extract数据
        testcase_extract_datas = testcase_request.get('test').get('extract')
        testcase_extract_datas_list = handle_datas.handle_data3(testcase_extract_datas)

        # 处理parameters数据
        testcase_parameters_datas = testcase_request.get('test').get('parameters')
        testcase_parameters_datas_list = handle_datas.handle_data3(testcase_parameters_datas)


        selected_configure_id = testcase_include.get('config')
        selected_modular_id = testcase_obj.modular_id
        selected_project_id = Modulars.objects.get(id=selected_modular_id).project_id
        selected_testcase_id = testcase_include.get('testcases')

        datas = {
            'author': testcase_obj.author,
            'testcase_name': testcase_obj.name,
            'selected_configure_id': selected_configure_id,
            'selected_modular_id': selected_modular_id,
            'selected_project_id': selected_project_id,
            'selected_testcase_id': selected_testcase_id,

            'method': testcase_request_datas.get('method'),
            'url': testcase_request_datas.get('url'),
            'param': testcase_params_list,
            'header': testcase_headers_list,
            'data': testcase_form_datas_list,
            'json': testcase_json_datas,

            'extract': testcase_extract_datas_list,
            'validate': testcase_validate_list,
            'globalVar': testcase_variables_list,
            'parameters': testcase_parameters_datas_list,
        }
        return Response(datas)

    @action(methods=['post'], detail=True)
    def run(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        datas = serializer.validated_data
        env_id = datas.get('env_id')
        testcase_dir_path = os.path.join(settings.SUITES_DIR, datetime.strftime(datetime.now(), '%Y%m%d%H%M%S%f'))
        os.mkdir(testcase_dir_path)
        env = Envs.objects.filter(id=env_id, is_delete=False).first()

        # 生成yaml用例文件
        common.generate_testcase_files(instance, env, testcase_dir_path)

        # 运行用例
        return common.run_testcase(instance, testcase_dir_path)

    def get_serializer_class(self):
        return serializers.TestcasesRunSerializer if self.action == 'run' else self.serializer_class















